package com.example.myapplication.widgets.pickerview.date;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

import com.example.myapplication.R;
import com.example.myapplication.utils.TimeUtils;
import com.example.myapplication.widgets.pickerview.base.IntPickerBean;
import com.example.myapplication.widgets.pickerview.base.PickerBean;
import com.example.myapplication.widgets.pickerview.base.PickerView;

import java.util.ArrayList;
import java.util.List;

public class DatePickerView extends ConstraintLayout {
    private PickerView mYearPicker;
    private PickerView mMonthPicker;
    private PickerView mDayPicker;
    private TextView mDayTitle;

    private OnSelectedListener mOnSelectedListener;

    private int mMinYear, mMinMonth, mMinDay;
    private int mMaxYear, mMaxMonth, mMaxDay;

    private int mSelectYear, mSelectMonth, mSelectDay;

    public DatePickerView(Context context) {
        this(context, null);
    }

    public DatePickerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DatePickerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        View view = View.inflate(context, R.layout.layout_date_picker_view, this);
        mYearPicker = view.findViewById(R.id.year);
        mMonthPicker = view.findViewById(R.id.month);
        mDayPicker = view.findViewById(R.id.day);
        mDayTitle = view.findViewById(R.id.dayTitle);

        mYearPicker.setTextSize(context.getResources().getDimensionPixelSize(R.dimen.textsize_18sp), context.getResources().getDimensionPixelSize(R.dimen.textsize_18sp));
        mMonthPicker.setTextSize(context.getResources().getDimensionPixelSize(R.dimen.textsize_18sp), context.getResources().getDimensionPixelSize(R.dimen.textsize_18sp));
        mDayPicker.setTextSize(context.getResources().getDimensionPixelSize(R.dimen.textsize_18sp), context.getResources().getDimensionPixelSize(R.dimen.textsize_18sp));
        mYearPicker.setTopBottomPadding(context.getResources().getDimensionPixelSize(R.dimen.left_right_space));
        mMonthPicker.setTopBottomPadding(context.getResources().getDimensionPixelSize(R.dimen.left_right_space));
        mDayPicker.setTopBottomPadding(context.getResources().getDimensionPixelSize(R.dimen.left_right_space));
        mYearPicker.setSelectedTextColor(ContextCompat.getColor(context, R.color.picker_view_sel_txt_color));
        mMonthPicker.setSelectedTextColor(ContextCompat.getColor(context, R.color.picker_view_sel_txt_color));
        mDayPicker.setSelectedTextColor(ContextCompat.getColor(context, R.color.picker_view_sel_txt_color));
        mYearPicker.setUnSelectTextColor(ContextCompat.getColor(context, R.color.picker_view_un_sel_txt_color));
        mMonthPicker.setUnSelectTextColor(ContextCompat.getColor(context, R.color.picker_view_un_sel_txt_color));
        mDayPicker.setUnSelectTextColor(ContextCompat.getColor(context, R.color.picker_view_un_sel_txt_color));
        mYearPicker.setCanScrollLoop(false);
        mMonthPicker.setCanScrollLoop(false);
        mDayPicker.setCanScrollLoop(false);
        mYearPicker.setSelectedOrientation(PickerView.SELECTED_ORIENTATION_CENTER);
        mMonthPicker.setSelectedOrientation(PickerView.SELECTED_ORIENTATION_CENTER);
        mDayPicker.setSelectedOrientation(PickerView.SELECTED_ORIENTATION_CENTER);
        mYearPicker.setUseTextSizeByScale(false);
        mMonthPicker.setUseTextSizeByScale(false);
        mDayPicker.setUseTextSizeByScale(false);
        mYearPicker.setNeedChangeAlpha(false);
        mMonthPicker.setNeedChangeAlpha(false);
        mDayPicker.setNeedChangeAlpha(false);

        mYearPicker.setLineInfo(context.getResources().getDimensionPixelSize(R.dimen.dp_45),
                context.getResources().getDimensionPixelSize(R.dimen.dp_05), ContextCompat.getColor(context, R.color.line_color));
        mMonthPicker.setLineInfo(context.getResources().getDimensionPixelSize(R.dimen.dp_45),
                context.getResources().getDimensionPixelSize(R.dimen.dp_05), ContextCompat.getColor(context, R.color.line_color));
        mDayPicker.setLineInfo(context.getResources().getDimensionPixelSize(R.dimen.dp_45),
                context.getResources().getDimensionPixelSize(R.dimen.dp_05), ContextCompat.getColor(context, R.color.line_color));

        mYearPicker.setOnSelectListener((pickerView, pickerBean, position) -> {
            if (pickerBean instanceof IntPickerBean) {
                mSelectYear = ((IntPickerBean) pickerBean).value;
                boolean isReselectMonth = refreshMonth();
                boolean isReselectDay = refreshDay();
                if (!isReselectMonth && !isReselectDay && mOnSelectedListener != null)
                    mOnSelectedListener.onSelected(mSelectYear, mSelectMonth, mSelectDay);
            }
        });
        mMonthPicker.setOnSelectListener((pickerView, pickerBean, position) -> {
            if (pickerBean instanceof IntPickerBean) {
                mSelectMonth = ((IntPickerBean) pickerBean).value;
                boolean isReselectDay = refreshDay();
                if (!isReselectDay && mOnSelectedListener != null)
                    mOnSelectedListener.onSelected(mSelectYear, mSelectMonth, mSelectDay);
            }
        });
        mDayPicker.setOnSelectListener((pickerView, pickerBean, position) -> {
            if (pickerBean instanceof IntPickerBean)
                mSelectDay = ((IntPickerBean) pickerBean).value;
            if (mOnSelectedListener != null)
                mOnSelectedListener.onSelected(mSelectYear, mSelectMonth, mSelectDay);
        });
    }

    public void onDestroy() {
        mYearPicker.onDestroy();
        mMonthPicker.onDestroy();
        mDayPicker.onDestroy();
    }

    public void setDayVisible(boolean visible) {
        if (visible) {
            mDayPicker.setVisibility(View.VISIBLE);
            mDayTitle.setVisibility(View.VISIBLE);
        } else {
            mDayPicker.setVisibility(View.GONE);
            mDayTitle.setVisibility(View.GONE);
        }
    }

    public void setDateInfo(String minDate, String maxData) {
        String[] minDateSplit;
        if (minDate.contains("-"))
            minDateSplit = minDate.split("-");
        else
            minDateSplit = minDate.split("/");

        String[] maxDateSplit;
        if (maxData.contains("-"))
            maxDateSplit = maxData.split("-");
        else
            maxDateSplit = maxData.split("/");

        try {
            mMinYear = Integer.parseInt(minDateSplit[0]);
            mMinMonth = Integer.parseInt(minDateSplit[1]);
            mMinDay = Integer.parseInt(minDateSplit[2]);
        } catch (Exception ignored) {
        }

        try {
            mMaxYear = Integer.parseInt(maxDateSplit[0]);
            mMaxMonth = Integer.parseInt(maxDateSplit[1]);
            mMaxDay = Integer.parseInt(maxDateSplit[2]);
        } catch (Exception ignored) {
        }

        List<IntPickerBean> yearList = new ArrayList<>();
        IntPickerBean yearBean;
        for (int i = mMinYear; i <= mMaxYear; i++) {
            yearBean = new IntPickerBean(i);
            yearList.add(yearBean);
        }
        mYearPicker.setDataList(new ArrayList<>(yearList));

        refreshMonth();
        refreshDay();
        selectDate(minDate);
    }

    private boolean refreshMonth() {
        List<IntPickerBean> monthList = new ArrayList<>();
        IntPickerBean monthBean;
        int min, max;
        // 最小和最大需要进行特殊处理
        if (mSelectYear == mMinYear) {
            min = mMinMonth;
            if (mMaxYear == mMinYear)
                max = mMaxMonth;
            else
                max = 12;
        } else if (mSelectYear == mMaxYear) {
            min = 1;
            max = mMaxMonth;
        } else {
            min = 1;
            max = 12;
        }
        for (int i = min; i <= max; i++) {
            monthBean = new IntPickerBean(i, 2);
            monthList.add(monthBean);
        }
        mMonthPicker.setDataList(new ArrayList<>(monthList));
        if (mSelectMonth < min || mSelectMonth > max) {
            if (mSelectMonth < min)
                mSelectMonth = min;
            else
                mSelectMonth = max;
            mMonthPicker.setSelected(mSelectMonth - min);
            return true;
        } else
            mMonthPicker.setSelected(mSelectMonth - min);
        return false;
    }

    private boolean refreshDay() {
        List<IntPickerBean> dayList = new ArrayList<>();
        IntPickerBean dayBean;
        int min, max;
        int totalDay = TimeUtils.getTotalDayOfMonth(mSelectYear, mSelectMonth);
        // 最小和最大需要进行特殊处理
        if (mSelectYear == mMinYear && mSelectMonth == mMinMonth) {
            min = mMinDay;
            if (mMaxYear == mMinYear && mMaxMonth == mMinMonth)
                max = mMaxDay;
            else
                max = totalDay;
        } else if (mSelectYear == mMaxYear && mSelectMonth == mMaxMonth) {
            min = 1;
            max = mMaxDay;
        } else {
            min = 1;
            max = totalDay;
        }
        for (int i = min; i <= max; i++) {
            dayBean = new IntPickerBean(i, 2);
            dayList.add(dayBean);
        }
        mDayPicker.setDataList(new ArrayList<>(dayList));
        if (mSelectDay < min || mSelectDay > max) {
            if (mSelectDay < min)
                mSelectDay = min;
            else
                mSelectDay = max;
            mDayPicker.setSelected(mSelectDay - min);
            return true;
        } else
            mDayPicker.setSelected(mSelectDay - min);
        return false;
    }

    public void selectDate(String date) {
        if (TextUtils.isEmpty(date)) return;
        String[] selectDateSplit = date.contains("-") ? date.split("-") : date.split("/");
        try {
            mSelectYear = Integer.parseInt(selectDateSplit[0]);
            mSelectMonth = Integer.parseInt(selectDateSplit[1]);
            mSelectDay = Integer.parseInt(selectDateSplit[2]);
        } catch (Exception ignored) {
        }

        for (PickerBean pickerBean : mYearPicker.getDataList()) {
            if (pickerBean.getText().equals(selectDateSplit[0])) {
                mYearPicker.setSelected(mYearPicker.getDataList().indexOf(pickerBean));
                break;
            }
        }
        for (PickerBean pickerBean : mMonthPicker.getDataList()) {
            if (pickerBean.getText().equals(selectDateSplit[1])) {
                mMonthPicker.setSelected(mMonthPicker.getDataList().indexOf(pickerBean));
                break;
            }
        }
        for (PickerBean pickerBean : mDayPicker.getDataList()) {
            if (pickerBean.getText().equals(selectDateSplit[2])) {
                mDayPicker.setSelected(mDayPicker.getDataList().indexOf(pickerBean));
                break;
            }
        }
    }

    public void setOnSelectedListener(OnSelectedListener onSelectedListener) {
        mOnSelectedListener = onSelectedListener;
    }

    public interface OnSelectedListener {
        void onSelected(int year, int monty, int day);
    }
}
